package jmind.asteroidea.plugin.spring;

import jmind.asteroidea.annotations.StarfishWristPoint;
import jmind.asteroidea.core.AsteroideaContextHolder;
import jmind.asteroidea.core.AsteroideaUtils;
import jmind.asteroidea.core.parser.OriginalTagParser;
import jmind.asteroidea.core.parser.TagParser;
import jmind.base.util.reflect.ClassCacheUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

/**
 * description:
 *
 * @author weibo.xie
 * @date:2022/7/7 下午3:07
 */
@Aspect
public class StartfishInterceptor {

    @Around(value = "@annotation(starfishWristPoint)", argNames = "pjp,starfishWristPoint")
    public Object doAround(ProceedingJoinPoint pjp, StarfishWristPoint starfishWristPoint) throws Throwable {
        try {
            if(OriginalTagParser.class.equals(starfishWristPoint.tagParser())){
                AsteroideaContextHolder.hold(starfishWristPoint.reducer(),starfishWristPoint.tags());
            }else {
                TagParser tagParser = ClassCacheUtil.getInstance().newInstance(starfishWristPoint.tagParser());
                /**
                 *  因为接口不能获取参数名称，这里统一成arg0 这样的形式
                 MethodSignature signature = (MethodSignature) pjp.getSignature();
                 String[] parse = tagParser.parse(starfishWristPoint.tags(), signature.getParameterNames(), pjp.getArgs());
                 **/
                Object[] args = pjp.getArgs();
                String[] parse = tagParser.parse(starfishWristPoint.tags(), AsteroideaUtils.createParamArgs(args), args);
                AsteroideaContextHolder.hold(starfishWristPoint.reducer(),parse);
            }
            return pjp.proceed();
        }finally {
            AsteroideaContextHolder.clear();
        }
    }
}
